package banco.facade;

import javax.ejb.Stateful;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import banco.entidades.Conta;
import banco.entidades.Usuario;

@Stateful
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public class FachadaBancoBean implements FachadaBanco {

	@PersistenceContext(unitName="bancoEJB")
	private EntityManager em;
	
	@Override
	public Conta recuperar(int contaId) {
		return em.find(Conta.class, contaId);
	}

	@Override
	public Usuario autenticar(String login, String senha) {
		try {
			return em.createNamedQuery("findByLoginSenha", Usuario.class)
				.setParameter("login", login)
				.setParameter("senha", senha)
				.getSingleResult();
		} catch(NoResultException ex) {
			return null;
		}
	}

	@Override
	public String titular(int contaId) {
		try {
			return em.createNamedQuery("findByConta", Usuario.class)
				.setParameter("conta", contaId)
				.getSingleResult()
				.getNome();
		} catch(NoResultException ex) {
			return null;
		}
	}

}
